package org.jash.utils.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import org.jash.utils.log
import org.jash.utils.Event
import org.jash.utils.bus
import java.lang.reflect.ParameterizedType

@Suppress("UNCHECKED_CAST")
abstract class BaseFragment<B:ViewDataBinding, VM:BaseViewModel<*, *>>: Fragment() {
    private val types by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    lateinit var binding:B
    lateinit var viewModel:VM
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val clazz = types[0] as Class<B>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        binding = method.invoke(null, inflater) as B
        viewModel = ViewModelProvider(this)[types[1] as Class<VM>]
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        observerBus()
        initData()
        initView()
    }
    private fun observerBus() {
        val methods = javaClass.declaredMethods
        for (method in methods) {
            val event = method.getAnnotation(Event::class.java)
            if (event != null) {
                bus.observe(viewLifecycleOwner) {
                    if (it.first == event.value) {
                        method.invoke(this, it.second)
                    }
                }
            }
        }
    }
    abstract fun initData()
    abstract fun initView()
    open fun error(throwable: Throwable) {
        Toast.makeText(requireContext(), throwable.message, Toast.LENGTH_SHORT).show()
        log(throwable.message)
    }
}